import type {Router} from 'vue-router'

import { PageNameEnum } from '@/enums/pageEnums'
import {
  router
} from '@/router'
import {
  userUserStore
} from '@/store/modules/user'
import NProgress from 'nprogress'




export function setupRouterGuard() {
  const whiteList = [PageNameEnum.LOGIN, PageNameEnum.NO_PERMISSION, PageNameEnum.NOT_FOUND]

  router.beforeEach((to, from, next) => {
    NProgress.start()
    const userStore = userUserStore()  // ! 只能在mounted后也就是在beforeEach后才能用
    const role: string = userStore.role
    if (whiteList.includes(<PageNameEnum>to.name)) {
      // 如果是login
      if (to.name == PageNameEnum.LOGIN) {
        // 如果已经有了role
        if (role) {
          next(from.path)
        } else {
          next()
        }
      } else {
        next()
      }
    } else {
      // 检查是否有权限访问
      if (to.meta.roles?.includes(role)) {
        next()
      } else {
        next('/no_permission')
      }
    }
  })

  router.afterEach(() => {
    NProgress.done()
  })
}


export function goToPermissionPage(navigate: Router,role: string) {
  if(role === '代销处用户') {
    navigate.push({name: PageNameEnum.GOOD_LIST})
  } else if(role === '公司销售主管') {
    navigate.push({name: PageNameEnum.LISTING})
  } else if(role === '公司营销主管') {
    navigate.push({name:PageNameEnum.USER_INFO})
  } else if(role === '公司财务主管') {
    navigate.push({name: PageNameEnum.SALE_INFO})
  } else if(role === '公司送货主管') {
    navigate.push({name:PageNameEnum.DELIVERY})
  }
}